package com.boding.power.common;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

import com.boding.power.model.Permissions;
import com.boding.power.model.Roles;
import com.boding.power.model.Users;

/**
 * 
 * @author giegie
 * @date 2016年4月17日
 * @description
 *  jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
 *  jdbcRealm.permissionsLookupEnabled = true
 *  jdbcRealm.authenticationQuery = SELECT password FROM users
 *  WHEREusername = ? jdbcRealm.userRolesQuery = SELECT r.role_name
 *  FROM roles AS r, user_roles AS ur WHERE r.id = ur.role_id AND
 *  ur.user_id = (SELECT id FROM users WHERE username = ?)
 *  jdbcRealm.permissionsQuery = SELECT p.permission FROM
 *  permissions AS p, roles_permissions AS rp WHERE p.id =
 *  rp.permission_id AND rp.role_id = (SELECT id FROM roles WHERE
 *  role_name = ?)
 */
public class ShiroDbRealm extends AuthorizingRealm {

	/**
	 * 认证回调函数,登录时调用.
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		Users user = Users.dao.findByUserNameAndPassword(token.getUsername(),
				String.valueOf(token.getPassword()));
		return user != null ? new SimpleAuthenticationInfo(token.getUsername(),
				String.valueOf(token.getPassword()), getName()) : null;
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String loginName = (String) principals.fromRealm(getName()).iterator()
				.next();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Roles role = Roles.dao
				.findFirst(
						"SELECT r.role_name FROM roles AS r, user_roles AS ur WHERE r.id = ur.role_id AND ur.user_id = (SELECT id FROM users WHERE username = ?)",
						loginName);
		if (null == role) {
			return info;
		}
		info.addRole(role.getRoleName());
		List<Permissions> permissions = Permissions.dao
				.find("SELECT p.permission FROM permissions AS p, roles_permissions AS rp WHERE p.id = rp.permission_id AND rp.role_id = (SELECT id FROM roles WHERE role_name = ?)",
						role.getRoleName());
		List<String> lists = new ArrayList<String>();
		for (Permissions s : permissions) {
			lists.add(s.getPermission());
		}
		info.addStringPermissions(lists);
		return info;
	}

	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}
}